# -*- coding: utf-8 -*-
# @Time    : 2018-05-30 12:17
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Rule33_UnpaidLoan_CorporationCnt.py
# @Software: PyCharm

'''eof
name:未结清贷款机构数（除住房按揭、汽车贷款）
code:UnpaidLoan_CorporationCnt
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']

def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData


def UnpaidLoan_CorporationCnt():
    try:
        icrLoanInfo002LoanList = FormatData("ICRLoanInfo002*Loan")
        if icrLoanInfo002LoanList in null_type_list or icrLoanInfo002LoanList == [{}]:
            return u"缺失值"
        returnList = []
        for icrLoanInfo002Loan in icrLoanInfo002LoanList:
            try:
                state = icrLoanInfo002Loan.get("State")
                loanType = icrLoanInfo002Loan.get("LoanType")
                financeOrg = icrLoanInfo002Loan.get("FinanceOrg")
                if state in null_type_list or loanType in null_type_list or financeOrg in null_type_list:
                    returnList.append(None)
                    continue
                if loanType not in (u"个人住房贷款", u"个人汽车消费贷款", u"个人住房公积金贷款") and \
                    u"重庆银行" not in financeOrg and state in [u"正常", u"逾期", u"呆账"]:
                    returnList.append(financeOrg)
                else:
                    returnList.append("None")
            except:
                returnList.append(None)
                continue
        returnListNotNone = filter(lambda x: x is not None, returnList)
        returnListNotNoneStr = filter(lambda x: x != "None", returnListNotNone)
        if len(returnListNotNone) == 0:
            return u"缺失值"
        elif len(returnListNotNoneStr) == 0:
            return 0
        else:
            return len(set(returnListNotNoneStr))

    except:
        return u"缺失值"

result = UnpaidLoan_CorporationCnt()